from select import poll
from select import POLLIN
import socket

tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
p = poll()
tcp_server.bind(("127.0.0.1", 9000))
tcp_server.listen(100)

p.register(tcp_server.fileno(), POLLIN)
clients = {}
while True:
    ready_fds = p.poll()
    for fd, ev in ready_fds:
        if fd == tcp_server.fileno():
            client,addr = tcp_server.accept()
            print("Client FD: {}".format(client.fileno()))
            p.register(client.fileno(), POLLIN)
            clients[client.fileno()] = client
            print(clients)
        else:
            try:
                client = clients[fd]
                data = client.recv(65535)
                if not data:
                    raise Exception
                print("Recv: {}".format(data.decode("utf-8")))
            except Exception as e:
                print(e)
                p.unregister(fd)
                p.register(fd, POLLIN)
                client.close()
                del clients[fd]
